<script setup lang="ts">
import { traduction, getErrorTranslate } from '@/utils/language';
import { ref, reactive, toRefs, watch, computed, onMounted } from 'vue';
import useStore from '@/stores';
import { UserPrivil } from '@/model/base-enum';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import Dialog from '@/components/Dialog/Dialog.vue';
import { resetFirmware, rollBackFirmware } from '../../upgrade.services';
import { showElMessage, getMessageId } from '@/utils/utils';
import { useRouter } from 'vue-router';
import { clearCurrentLoginInfo } from '@/utils/common-service';
import { setStoreData } from '@/utils/composition';
import VersionCard from './VersionCard.vue';

const router = useRouter();
const store = useStore();
// 系统锁定状态
const isSystemLock = computed(() => {
  return store.state.glob.systemLocked;
});
// 查询升级状态
const isUpgrading = computed(() => {
  return store.state.glob.isUpgrading;
});
const isPrivileges = checkPrivil(UserPrivil.baseConfig);
const isActive = computed(() => {
  return store.state.glob.isActive;
});

const dialogRef = ref();
const props = defineProps({
  firmwareVersion: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  upgradeVersion: {
    required: true,
    type: Object,
    default: () => {
      return {};
    },
  },
  versionList: {
    required: true,
    type: Array,
    default: () => {
      return [];
    },
  },
});

const { firmwareVersion, upgradeVersion, versionList } = toRefs(props);
const firmwareLabel = reactive({
  mainLabel: traduction('IBMC_AVAILABLE_AZVERSION', {
    softwareName: store.state.loct.sn,
  }),
  activeLabel: traduction('IBMC_FIRMWARE_IMG_VERSION', {
    softwareName: store.state.loct.sn,
  }),
  backupLabel: traduction('IBMC_IBMC_IMG_VERSION_TWO', {
    softwareName: store.state.loct.sn,
  }),
});
const bmcVersionLabel = reactive({
  label: traduction('IBMC_VERSION_BMC', {
    softwareName: store.state.loct.sn,
  }),
});

const lcnMappingList = reactive({
  Patch: 'IBMC_LCN_PATCH_VERSION',
  Software: 'IBMC_LCN_SOFTWARE_VERSION',
});

const dialogConfig = reactive({
  value: '',
  id: '',
  content: traduction('COMMON_ASK_OK'),
  title: traduction('ALARM_OK'),
});

// BMC各类型版本数据
const bmcVersion = ref<any[]>([]);
const productVersion = ref<any[]>([]);
const riserCardVersion = ref<any[]>([]);
const hddVersion = ref<any[]>([]);
const cpuVersion = ref<any[]>([]);
const expVersion = ref<any[]>([]);
const fanVersion = ref<any[]>([]);
const peuVersion = ref<any[]>([]);
const nicVersion = ref<any[]>([]);
const powerVersion = ref<any[]>([]);
const sdiVersion = ref<any[]>([]);
const lcnVersion = ref<any[]>([]);

// dialog框开启
function resetDialog(id: any) {
  switch (id) {
    case 'restBut':
      dialogConfig.value = 'restBut';
      dialogConfig.content = traduction('IBMC_REST_IBMC_TIP', {
        softwareName: store.state.loct.sn,
      });
      break;
    case 'backBut':
      dialogConfig.value = 'backBut';
      dialogConfig.content = upgradeVersion.value.unavailable
        ? traduction('IBMC_MAIN_ROLLBACK_TIP_TWO')
        : traduction('IBMC_MAIN_ROLLBACK_TIP');
      break;
    default:
      break;
  }
  dialogRef.value.show();
}
// dialog框关闭
function dialogClose(reason: any) {
  dialogRef.value.hide();
  if (reason) {
    switch (dialogConfig.value) {
      case 'restBut':
        resets();
        break;
      case 'backBut':
        rollBacks();
        break;
      default:
        break;
    }
  }
}
// 重启IBMC
function resets() {
  const restParams = {};
  resetFirmware(restParams)
    .then(res => {
      localStorage.setItem('firmwareToLogin', 'true');
      router.push('/login');
      clearCurrentLoginInfo();
      setStoreData('loct', 'isExited', true);
    })
    .catch(error => {
      const errorId = getMessageId(error.data);
      const errorMsg = getErrorTranslate(errorId[0].code as string);
      showElMessage('error', errorMsg);
    });
}
// 主备镜像倒换
function rollBacks() {
  const query = {};
  rollBackFirmware(query)
    .then(res => {
      showElMessage('success', traduction('COMMON_SUCCESS'));
      setTimeout(() => {
        localStorage.setItem('firmwareToLogin', 'true');
        clearCurrentLoginInfo();
        router.push('/login');
      }, 3000);
    })
    .catch(error => {
      const errorId = getMessageId(error.data);
      const errorMsg = getErrorTranslate(errorId[0].code as string);
      showElMessage('error', errorMsg);
    });
}

function getBMCVersionList(): Array<any> {
  const data = [
    {
      name: firmwareLabel.activeLabel,
      currentVersion: props.firmwareVersion.activeBMCVersion,
      id: 'upActive',
    },
    {
      name: firmwareLabel.backupLabel,
      currentVersion: props.firmwareVersion.backupBMCVersion,
      id: 'upBack',
    },
  ];
  if (props.upgradeVersion.unavailable) {
    data.push({
      name: firmwareLabel.mainLabel,
      currentVersion: props.firmwareVersion.availableBMCVersion,
      id: 'upAvailable',
    });
  }
  return data;
}

function getVersionList(vsList: Array<any>, type: string): Array<any> {
  return (vsList || []).filter(e => e.type === type);
}

function getTraVersionList(vsList: Array<any>, type: string, mappingList: any): Array<any> {
  let showList = [] as any;
  (vsList || []).filter(e => e.type === type).forEach((item, index) => {
    const boardIndex = item.name.match(/\d+/)?.[0];
    const boardType = item.name.split(' ')?.[1] || '';
    const canGetIndex = boardIndex || boardIndex === 0;
    if (canGetIndex && boardType && item.currentVersion !== '--' ) {
      showList.push({
        name: traduction(mappingList[boardType] || '', { boardIndex }),
        currentVersion: item.currentVersion,
        id: `LCN${index}`,
      });
    }
  });
  return showList;
}

watch(
  () => props.firmwareVersion,
  () => {
    bmcVersion.value = getBMCVersionList();
  },
  { deep: true },
);
watch(
  () => props.versionList,
  () => {
    productVersion.value = getVersionList(props.versionList, 'Product');
    riserCardVersion.value = getVersionList(props.versionList, 'Riser');
    hddVersion.value = getVersionList(props.versionList, 'DiskBP');
    cpuVersion.value = getVersionList(props.versionList, 'CpuBoard');
    expVersion.value = getVersionList(props.versionList, 'ExpBoard');
    fanVersion.value = getVersionList(props.versionList, 'FanBoard');
    peuVersion.value = getVersionList(props.versionList, 'PeuBoard');
    nicVersion.value = getVersionList(props.versionList, 'NIC');
    powerVersion.value = getVersionList(props.versionList, 'Power');
    sdiVersion.value = getVersionList(props.versionList, 'SDI');
    lcnVersion.value = getTraVersionList(props.versionList, 'LCN', lcnMappingList);
  },
  { deep: true },
);
</script>
<template>
  <div id="versionView" class="page-container">
    <div class="btn-group">
      <el-button
        id="restBut"
        :disabled="isSystemLock || !isPrivileges || isUpgrading || isActive"
        type="primary"
        @click="resetDialog('restBut')"
      >
        {{ $t('IBMC_REST_IBMC', { softwareName: store.state.loct.sn }) }}
      </el-button>
      <el-button
        id="backBut"
        :disabled="isSystemLock || !isPrivileges || isUpgrading || isActive"
        type="primary"
        @click="resetDialog('backBut')"
      >
        {{ $t('IBMC_MAIN_ROLLBACK_TWO') }}
      </el-button>
      <Dialog ref="dialogRef" :config="dialogConfig" @close="dialogClose"></Dialog>
    </div>
    <div id="versionTab" class="version-list">
      <div class="version-title">{{ $t('IBMC_VERSION_LIST') }}</div>
      <div class="card-container">
        <VersionCard :title="bmcVersionLabel.label" :version-list="bmcVersion" />
        <VersionCard :title="$t('IBMC_VERSION_PRODUCT')" :version-list="productVersion" />
        <VersionCard :title="$t('IBMC_VERSION_RISER')" :version-list="riserCardVersion" />
        <VersionCard :title="$t('IBMC_VERSION_DISK_BP')" :version-list="hddVersion" />
        <VersionCard :title="$t('IBMC_VERSION_CPU_BOARD')" :version-list="cpuVersion" />
        <VersionCard :title="$t('IBMC_VERSION_EXP_BOARD')" :version-list="expVersion" />
        <VersionCard :title="$t('IBMC_VERSION_FAN_BOARD')" :version-list="fanVersion" />
        <VersionCard :title="$t('IBMC_VERSION_NIC')" :version-list="nicVersion" />
        <VersionCard :title="$t('IBMC_VERSION_POWER')" :version-list="powerVersion" />
        <VersionCard :title="$t('IBMC_VERSION_PEU')" :version-list="peuVersion" />
        <VersionCard :title="$t('IBMC_VERSION_SDI')" :version-list="sdiVersion" />
        <VersionCard :title="$t('IBMC_VERSION_LCN')" :version-list="lcnVersion" />
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.page-container {
  .btn-group {
    margin-bottom: 16px;

    .el-button {
      min-width: 128px;
    }
  }

  .version-list {
    margin-top: 16px;
  }

  .version-title {
    margin-bottom: 16px;
    font-size: 16px;
    color: var(--o-text-color-primary);
  }

  .card-container {
    flex-direction: row;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
